package cn.jdy.dzdd.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.dzdd.entity.DzddSecretaryMail;
import cn.jdy.dzdd.service.DzddSecretaryMailService;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.NginxPurgeCacheUtil;


/**
 * @desc 队长信箱操作类
 * @author ningqian
 * @data 2017-6-9
 */

@Controller
@RequestMapping("/dzddMail")
public class DzddSecretaryMailCtrl extends BaseCtrl {
	
	@Autowired
	private DzddSecretaryMailService dzddSecretaryMailService;
	//默认列表路径
	private static String viewName = "redirect:/dzddMail/list?s=";
	
	/**
	 * 地质大队
	 * 初始化,仅作页面跳转作用
	 * @return
	 */
	@RequestMapping("/list")
	public ModelAndView list(DzddSecretaryMail entity, String fromDate, String toDate, @RequestParam(required = false) Character s) {
		ModelAndView mv = new ModelAndView("/operate/mailList.jsp");
		if(s != null)
			switch(s) {
				case '1': mv.addObject("msg", "成功！");break;
				case '2': mv.addObject("msg", "更新成功！");break;
				case '3': mv.addObject("msg", "删除成功！");break;
				case '4': mv.addObject("msg", "操作失败！");break;
				default: break;
			}
		mv.addObject("entity", entity);
		mv.addObject("fromDate", fromDate);
		mv.addObject("toDate", toDate);
		return mv;
	}
	
	
	/**
	 * 地质大队队长信息
	 * 异步查询
	 * @param news
	 * @return
	 */
	@RequestMapping("/queryByPage")
	@ResponseBody
	public Map<String, Object> queryByPage(DzddSecretaryMail mail, String fromDate, String toDate) {
		Map<String, Object> jsonMap = new HashMap<String, Object>();
		try {
			jsonMap.put("dataList", dzddSecretaryMailService.query(mail,fromDate, toDate));
			jsonMap.put("iTotalDisplayRecords", dzddSecretaryMailService.count(mail, fromDate, toDate));
			jsonMap.put("iTotalRecords", dzddSecretaryMailService.count());
		} catch(Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return jsonMap;
	}
	
	/**
	 * 查看详情
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/operate/mailDetail.jsp");
		mv.addObject("data", dzddSecretaryMailService.find(id));
		return mv;
	}
	
	
	/**
	 * 删除信件
	 * @return
	 */
	@RequestMapping("/del/{id}")
	public ModelAndView del(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView();
		try {
			this.dzddSecretaryMailService.delete(id);
			mv.setViewName(this.viewName.concat("3"));
			// 清理文章缓存
            NginxPurgeCacheUtil.purge(2, id);
		} catch(Exception e) {
			mv.setViewName(this.viewName.concat("4"));
			BaseLog.e(getClass(), "删除异常！", e);
		}
		return mv;
	}
	
	/** 
     * 下载文件 
     * @param id appid 
     * @param response 
     */  
    @RequestMapping(value="/download/{id}")  
    public void download(@PathVariable Long id, HttpServletResponse response){  
        String filepath = ""; 
        DzddSecretaryMail mail = dzddSecretaryMailService.find(id);
        if(mail.getWordFile() == null){  
            return;  
        }  
        
        String path = request.getSession().getServletContext().getRealPath("/");
        filepath = new File(path).getParent()+mail.getWordFile();  
          
        File file = new File(filepath);  
        InputStream inputStream = null;  
        OutputStream outputStream = null;  
        byte[] b= new byte[1024];  
        int len = 0;  
        try {  
            inputStream = new FileInputStream(file);  
            outputStream = response.getOutputStream();  
              
            response.setContentType("application/force-download");  
            String filename = file.getName();  
//            filename = filename.substring(36, filename.length());  
            response.addHeader("Content-Disposition","attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));  
            response.setContentLength( (int) file.length( ) );  
              
            while((len = inputStream.read(b)) != -1){  
                outputStream.write(b, 0, len);  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }finally{  
            if(inputStream != null){  
                try {  
                    inputStream.close();  
                    inputStream = null;  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
            if(outputStream != null){  
                try {  
                    outputStream.close();  
                    outputStream = null;  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
    }  

	
	
}
